package com.zhumo.sz.http;

import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

public class HttpTest {

    public static final  String OPENDATA_SZ_APP_KEY = "bb1443e5905a4bb9a94549bad75e3c30"; //开放平台接口appKey
    public static final  String OPENDATA_SZ_REQUEST_PREFIX = "https://opendata.sz.gov.cn/api/";

    public static void main(String[] args) throws IOException {
        HttpGet httpGet = makeOpenGovRequest(OPENDATA_SZ_APP_KEY, "29200_00403624/1", "20210101", "20211231", "10");
        CloseableHttpClient aDefault = HttpClients.createDefault();
        CloseableHttpResponse response = aDefault.execute(httpGet);
        String json = EntityUtils.toString(response.getEntity());
        System.out.println(json);
    }

    public static HttpGet makeOpenGovRequest(String appKey, String apiId, String startDate, String endDate, String rows) {
        String url = OPENDATA_SZ_REQUEST_PREFIX + apiId + "/service.xhtml";
        HttpGet httpGet = null;
        try {
            URIBuilder builder = new URIBuilder(url);
            builder.setParameter("page","1");
            builder.setParameter("rows", rows);
            builder.setParameter("appKey", appKey);
            if (endDate != null && startDate != null) {
                //必须同时填写起始日期和结束日期
                builder.setParameter("startDate", startDate);
                builder.setParameter("endDate", endDate);
            }
            URI uri = builder.build();
            System.out.println(uri);
            httpGet = new HttpGet(uri);
            httpGet.setHeader("Accept", ContentType.APPLICATION_JSON.getMimeType());
            httpGet.setHeader("Accept-Charset", "UTF-8");
        }catch (URISyntaxException e){
            e.printStackTrace();
        }
        return httpGet;
//
//        return CustomLogServerConfig.OPENDATA_SZ_REQUEST_PREFIX + apiId + "/service.xhtml?" +  "/page=1" + "&rows=" + rows + "&appKey=" + appKey
//        + "&startDate=" + startDate + "&endDate" + endDate;
        //不用返回字符串,直接返回请求体
    }

}
